package com.seecen.HJM.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.HJM.constant.MessageConstant;
import com.seecen.HJM.enumeration.BannerStatusEnum;
import com.seecen.HJM.model.dto.BannerDto;
import com.seecen.HJM.model.entity.Banner;
import com.seecen.HJM.result.DataVo;
import com.seecen.HJM.result.PageResult;
import com.seecen.HJM.service.BannerService;
import com.seecen.HJM.mapper.BannerMapper;
import com.seecen.HJM.service.MinioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
* @author 李龙
* @description 针对表【tb_banner】的数据库操作Service实现
* @createDate 2025-09-26 14:16:27
 *
*/
@Service
@CacheConfig(cacheNames = "bannerCache")
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner>
    implements BannerService{
    @Autowired
    private BannerMapper mapper;

    @Autowired
    private MinioService minioService;
    /*
    * 缓存：
    * 1.开启缓存机制
    * 在启动类上添加@EnableCaching 注解 开启缓存支持
    * 2.配置缓存
    * 在yml中配置
    * 3.使用
    * 在方法上添加@Cacheable 注解
    * 4.更新和清除
    * @CachePut：更新
    * @CacheEvict：删除
    * */


    //查询
    @Override
    @Cacheable(key = "'bannerList' + #bannerDto.pageNum + #bannerDto.pageSize + #bannerDto.bannerStatus")//缓存
    public DataVo<PageResult<Banner>> getBanner(BannerDto bannerDto) {
        //分页
        Page<Banner> bannerIPage=new Page<>(bannerDto.getPageNum(),bannerDto.getPageSize());
        QueryWrapper<Banner> bannerQueryWrapper=new QueryWrapper<>();
        if (bannerDto.getBannerStatus() != null) {
            bannerQueryWrapper.eq("status", bannerDto.getBannerStatus().getId());
        }
        IPage<Banner> bannerPage = mapper.selectPage(bannerIPage, bannerQueryWrapper);
        if (bannerPage.getRecords().size() == 0) {
            return DataVo.success(MessageConstant.DATA_NOT_FOUND, new PageResult<>(0L, null));
            //MessageConstant 进行字符串拼接
            //返回字符串结果
        }
        return DataVo.success(new PageResult<>(bannerPage.getTotal(), bannerPage.getRecords()));

    }

    //添加
    @Override
    @CacheEvict(cacheNames = "bannerCache", allEntries = true)//清除所有缓存
    public DataVo addBanner(String url) {
        //新建对象
        Banner banner=new Banner();
        banner.setBannerUrl(url);
        banner.setBannerStatus(BannerStatusEnum.ENABLE);

        //判断是否存在
        if (mapper.insert(banner)==0){
            //存在，添加失败
            return DataVo.error(MessageConstant.ADD + MessageConstant.FAILED);
        }
        //不存在，添加成功
        return DataVo.success(MessageConstant.ADD + MessageConstant.SUCCESS);
    }

    //修改轮播图
    @Override
    @CacheEvict(cacheNames = "bannerCache", allEntries = true)//清除所有缓存
    public DataVo updateBanner(Long bannerId, String url) {
        //通过对应id查找到对应轮播图
        Banner banner = mapper.selectById(bannerId);
        String oldUrl=banner.getBannerUrl();
        //删除oldUrl
        if (oldUrl!=null & !oldUrl.isEmpty()){
            //存在
            minioService.deleteFile(oldUrl);
        }
        //修改为新url
        banner.setBannerUrl(url);
        //判断是否修改成功
        if (mapper.updateById(banner)==0){
            //输出 修改失败
            return DataVo.error(MessageConstant.UPDATE + MessageConstant.FAILED);
        }
        //输出 修改成功
        return DataVo.success(MessageConstant.UPDATE + MessageConstant.SUCCESS);
    }

    //修改状态
    @Override
    @CacheEvict(cacheNames = "bannerCache", allEntries = true)//清除所有缓存
    public DataVo updateStatus(Long bannerId, Integer bannerStatus) {
        //判断要修改轮播图状态是否符合规范
        //获取轮播图状态
        BannerStatusEnum bannerStatusEnum;
        //进行判断
        if (bannerStatus==0){
            bannerStatusEnum=BannerStatusEnum.ENABLE;
        }else if (bannerStatus==1){
            bannerStatusEnum=BannerStatusEnum.DISABLE;
        }else {
            //不符合规范 输出状态无效
            return DataVo.error(MessageConstant.BANNER_STATUS_INVALID);
        }

        //获取轮播图状态，进行修改
        /*
        * 两种方法
        * 1.直接修改对象
        * 优点：性能消耗低
        * 缺点：会有线程安全问题
        *
        * 2.新建对象进行修改
        * 优点：线程安全
        * 缺点：性能消耗高
        * */
        Banner banner=new Banner();
        banner.setId(bannerId);
        banner.setBannerStatus(bannerStatusEnum);

        //判断修改是否成功
        if (mapper.updateById(banner) == 0) {
            //失败
            return DataVo.error(MessageConstant.UPDATE + MessageConstant.FAILED);
        }
        //成功
        return DataVo.success(MessageConstant.UPDATE + MessageConstant.SUCCESS);
    }

    @Override
    @CacheEvict(cacheNames = "bannerCache", allEntries = true)//清除所有缓存
    public DataVo deleteBanner(Long bannerId) {
        //判断是否存在
        Banner banner=mapper.selectById(bannerId);
        if (banner==null){
            return DataVo.error(MessageConstant.DATA_NOT_FOUND);
        }
        //存在 先进行minio的删除
        String bannerUrl = banner.getBannerUrl();
        if (bannerUrl != null && !bannerUrl.isEmpty()) {
            minioService.deleteFile(bannerUrl);
        }
        //判断是否删除成功
        if (mapper.deleteById(bannerId)==0){
            //删除失败 输出
            return DataVo.error(MessageConstant.DELETE + MessageConstant.FAILED);
        }
        //成功
        return DataVo.success(MessageConstant.DELETE + MessageConstant.SUCCESS);
    }

    //批量删除
    //
    @Override
    public DataVo deleteBannerList(List<Long> bannerIds) {
        //获取删除轮播图列表
        List<Banner> banners=mapper.selectByIds(bannerIds);
        //获取对应的url
        //使用了stream数据流
        List<String> urlList=banners.stream()//将集合转换为流 方便进行函数操作
                .map(Banner::getBannerUrl)//获取每个对象的url
                .filter(url -> url != null && !url.isEmpty())//过滤null和空字符串
                .toList();//将流转换为list集合
        //遍历url 删除minio中对应文件
        urlList.forEach(url -> minioService.deleteFile(url));
        //判断删除是否成功
        if (mapper.deleteByIds(bannerIds)==0){
            //失败
            return DataVo.error(MessageConstant.DELETE + MessageConstant.FAILED);
        }
        //成功
        return DataVo.success(MessageConstant.DELETE + MessageConstant.SUCCESS);
    }


}




